package com.ffcs.trino.config;

import com.ffcs.trino.domin.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangzhengxing
 */
@Component
@Slf4j
public class TrinoJdbc {

  private final String url = "jdbc:trino://localhost:8080/catalog";

  private final String user = "admin";


  public List<Map<String, Object>> getTrinoData(String query) {
    List<Map<String, Object>> resultList = new ArrayList<>();

    try {
      // 加载Trino JDBC驱动
      Class.forName("io.trino.jdbc.TrinoDriver");
      Connection connection = DriverManager.getConnection(url, user, null);
      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(query);

      // 获取结果集元数据
      ResultSetMetaData metaData = resultSet.getMetaData();
      int columnCount = metaData.getColumnCount();

      while (resultSet.next()) {
        HashMap<String, Object> row = new HashMap<>();
        for (int i = 1; i <= columnCount; i++) {
          String columnName = metaData.getColumnName(i);
          Object columnValue = resultSet.getObject(i);
          row.put(columnName, columnValue);
        }
        resultList.add(row);
      }

      resultSet.close();
      statement.close();
      connection.close();
    } catch (Exception e) {
      throw new RuntimeException("查询异常:" + e.getMessage());
    }

    return resultList;
  }


  /**
   * 错误检测
   *
   * @param query
   * @return
   */
  public ResponseData getTestConnection(String dataBase) {
    try {
      Class.forName("io.trino.jdbc.TrinoDriver");
      Connection connection = DriverManager.getConnection(url, user, null);
      Statement statement = connection.createStatement();
      String sql = "SELECT 1 FROM " + dataBase + ".information_schema.tables";
      log.info("查询的库: " + sql);
      ResultSet resultSet = statement.executeQuery(sql);

      // 获取结果集元数据
      ResultSetMetaData metaData = resultSet.getMetaData();
      int columnCount = metaData.getColumnCount();
      log.info("查询结果集合:" + columnCount);

      while (resultSet.next()) {
      }

      resultSet.close();
      statement.close();
      connection.close();
    } catch (Exception e) {
      return new ResponseData(500, e.getMessage());
    }

    return new ResponseData(200, "连接成功");
  }
}
